package com.jmz.apt.api.controller;

import com.jmz.apt.api.Helper.ResponseHelper;
import com.jmz.apt.api.Utils.JsonSerializerUtil;
import com.jmz.apt.api.common.AptConstant;
import com.jmz.apt.api.common.SecurityContextHolder;
import com.jmz.apt.api.dao.AdminRoleDao;
import com.jmz.apt.api.dto.impl.AdminResDto;
import com.jmz.apt.api.dto.impl.AdminResourceDto;
import com.jmz.apt.api.dto.impl.AdminTokenDto;
import com.jmz.apt.api.dto.impl.AdminUserDto;
import com.jmz.apt.api.entity.dbEntity.JmzAdminResource;
import com.jmz.apt.api.entity.dbEntity.JmzAdminRole;
import com.jmz.apt.api.entity.dbEntity.JmzAdminUser;
import com.jmz.apt.api.enums.ResponseCode;
import com.jmz.apt.api.enums.RoleCode;
import com.jmz.apt.api.message.request.RequestMessage;
import com.jmz.apt.api.message.response.ResponseMessage;
import com.jmz.apt.api.service.MenuService;
import org.modelmapper.ModelMapper;
import org.modelmapper.TypeToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by fanglexue on 2019/10/28.
 */

@RestController
@RequestMapping("/menu")
public class MenuController {

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    RedisTemplate<String, Serializable> redisTemplate;

    @Autowired
    private MenuService menuService;

    @RequestMapping(value="/menuList",method= RequestMethod.POST)
    @ResponseBody
    public ResponseMessage getMenus(@RequestBody RequestMessage requestMessage){
        AdminTokenDto agent = SecurityContextHolder.getAgent();
        String resources = stringRedisTemplate.opsForValue().get(AptConstant.Redis.ROLE_PREFIX + agent.getRoleId().toString());

        List<AdminResourceDto> menus = new ArrayList<>();
        if(agent.getRoleId()== RoleCode.ROLE_ADMIN.getType()){
            menus = menuService.getList();
        }else{
            menus = JsonSerializerUtil.string2Obj(resources,ArrayList.class,AdminResourceDto.class);
        }

       // 封装树形结构菜单列表
        List<AdminResourceDto> list = new ArrayList<>();
        if(!CollectionUtils.isEmpty(menus))
            list = menuService.encapsulationMenus(menus);

        //Set response data
        ResponseHelper responseHelper = new ResponseHelper();
        responseHelper.setResponseDataSet("菜单列表",list);
        responseHelper.setResponseBCode(ResponseCode.SUCCESS.getCode(),ResponseCode.SUCCESS.getDesc());

        ResponseMessage responseResult = responseHelper.getResponseMessageTemplate().getResponseMessage();
        return  responseResult;
    }


}
